﻿using Newtonsoft.Json;
using Survey.DataAccessLayer;
using Survey.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebUI.Controllers
{
    public class ApiController : Controller
    {
        #region 用户管理
        private UserAccessor userAccessor = new UserAccessor();
        // Api/LoginUser
        [HttpPost]
        public JsonResult Users(User user)
        {
            if (!ModelState.IsValid)
            {
                return Json(new { Result = false });
            }
            if (user.PasswordHash == "" || user.Email == "")
                return Json(new { Result = false });
            //验证失败将返回异常
            try
            {
                User tempUser = userAccessor.UserValidation(user.Email, user.PasswordHash);
                HttpSessionStateBase session = HttpContext.Session;
                session["curentUserId"] = tempUser.Id;
                return Json(new { Result = true });
            }
            catch (System.Exception)
            {
                return Json(new { Result = false });
            }
        }
        // Api/EditUser
        public JsonResult EditUser(User tempUser)
        {
            bool isOk = false;
            if (!ModelState.IsValid || string.IsNullOrEmpty(tempUser.PasswordHash) || string.IsNullOrEmpty(tempUser.Email))
            {
                return Json(new { Result = false });
            }


            var curentUserId = HttpContext.Session["curentUserId"];
            //没有登陆
            if (curentUserId == null)
            {
                return Json(new { Result = false });
            }

            User user = userAccessor.GetUserById((int)curentUserId);
            if (user == null)
                return Json(new { Result = false });
            user.Email = tempUser.Email;
            isOk = userAccessor.Modify(user, tempUser.PasswordHash);

            return Json(new { Result = isOk });

        }
        //Api/regUser
        public JsonResult RegUser(User user)
        {
            if (String.IsNullOrEmpty(user.Email) || String.IsNullOrEmpty(user.PasswordHash))
            {
                return Json(new { Result = false });
            }
            userAccessor.Add(user.Email, user.PasswordHash, new List<Questionnaire>());
            bool isOk = userAccessor.Save() > 0;
            return Json(new { Result = isOk });
        }
        //api/LoginOutUser
        public JsonResult LoginOutUser(User user)
        {
            //获取当前用户的在Session里的Id
            var session = HttpContext.Session;
            var curentUserId = session["curentUserId"];
            if (curentUserId == null)
            {
                return Json(new { Result = false });
            }
            session["curentUserId"] = null;
            return Json(new { Result = true }, JsonRequestBehavior.AllowGet);
        }
        // api/DetailedUser
        public JsonResult DetailedUser()
        {
            var curentUserId = HttpContext.Session["curentUserId"];

            if (curentUserId == null)
                return Json(new { Result = false });

            var user = userAccessor.GetUserById((int)curentUserId);

            if (user == null)
                return Json(new { Result = false });

            user.PasswordHash = "";
            var ret = Obj2Json(user);
            return Json(ret, JsonRequestBehavior.AllowGet);
        }
        #endregion


        #region Helper
        //解决Self loop问题
        private String Obj2Json(Object obj)
        {
            
            JsonSerializerSettings setting = new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                Formatting = Formatting.None
            };
            var ret = JsonConvert.SerializeObject(obj, setting);
            return ret;
        }
        #endregion


        #region 问卷管理
        private QuestionnaireAccessor questionnaireAccessor = new QuestionnaireAccessor();

        //api/GetQuestionnaireById
        public JsonResult GetQuestionnaireById(int id)
        {
            try
            {
                Questionnaire questionnaire = questionnaireAccessor.GetQuestionnaireById(id);
                return Json(Obj2Json(questionnaire), JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {

                return Json(new Questionnaire
                {
                    Describe = "无此ID问卷，异常",
                    Id = id,
                    QuestionCollection = null,
                    Title = "无此ID问卷，异常",
                }, JsonRequestBehavior.AllowGet);
            }
        }
        // api/GetAllQuestionnaire
        public JsonResult GetAllQuestionnaire()
        {
            var qs = questionnaireAccessor.Select(q => true);
            return Json(Obj2Json(qs), JsonRequestBehavior.AllowGet);
        }
        #endregion



        #region 答卷管理
        QuestionFeedbackAccessor feedbackAccessor = new QuestionFeedbackAccessor();
        //api/PostQuestionFeedback
        public JsonResult PostQuestionFeedback(List<int> IdCollection)
        {
            foreach (var item in IdCollection)
            {
                feedbackAccessor.Add(new QuestionFeedback
                {
                    QuestionOptionId = item
                });
            }
            bool isOk = feedbackAccessor.Save()>0;
            return Json(new { Result = isOk });
        }
        #endregion
    }
}